package com.jock.zjaddressanddatepicker.pickerview.dao;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DBManager {
    public static final String DB_NAME = "regions.db"; //保存的数据库文件名
    public static final String PACKAGE_NAME = "com.jock.zjaddressanddatepicker";
    public static final String DB_PATH = "/data/data/" + PACKAGE_NAME + "/databases/";
    private SQLiteDatabase database;
    private Activity context;
 
   public  DBManager(Activity context) {
        this.context = context;
    }
 
    public SQLiteDatabase openDatabase() {
        this.database = this.openDatabase(DB_PATH  + DB_NAME);
        return  this.database;
    }
 
    private SQLiteDatabase openDatabase(String dbfile) {
        try {
            initView(this.context);
            SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile,  null);
            return db;
        } catch (Exception e) {
            Log.e("Database", "database cloud not open!");
            e.printStackTrace();
        }
        return null;
    }
    private void initView(Activity context)
    {
        // 检查 SQLite 数据库文件是否存在
        if ((new File(DB_PATH + DB_NAME)).exists() == false)
        {
            // 如 SQLite 数据库文件不存在，再检查一下 database 目录是否存在
            File f = new File(DB_PATH);
            // 如 database 目录不存在，新建该目录
            if (!f.exists())
            {
                f.mkdir();
            }
            try {
                InputStream is = context.getBaseContext().getAssets().open(DB_NAME);
                FileOutputStream os = new FileOutputStream(DB_PATH + DB_NAME);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = is.read(buffer)) > 0)
                {
                    os.write(buffer, 0, length);
                }
                os.flush();
                os.close();
                is.close();
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    public void closeDatabase() {
        this.database.close();
    }
}
